// pages/user-records/user-records.js
const app = getApp()

Page({
  data: {
    records: [],
    loading: true,
    refreshing: false,
    currentPage: 1,
    hasMore: true,
    dateRange: {
      start: '',
      end: ''
    },
    // 统计数据
    totalQuantity: 0,
    totalWage: 0,
    pendingCount: 0
  },

  onLoad() {
    this.loadRecords()
  },

  onShow() {
    this.loadRecords()
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true,
      currentPage: 1,
      hasMore: true
    })
    this.loadRecords().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreRecords()
    }
  },

  // 加载记录列表
  loadRecords() {
    this.setData({
      loading: true
    })

    return app.userRequest({
      url: '/getRecords',
      data: {
        page: 1,
        start_date: this.data.dateRange.start,
        end_date: this.data.dateRange.end
      }
    }).then((res) => {
      // 修复：使用正确的数据字段
      const records = res.data?.list || res.data || []
      console.log('获取到的报工记录:', records)
      
      // 过滤掉不完整的记录（订单号、工序等为空的记录）
      const validRecords = records.filter(record => 
        record.order_no && 
        record.process_name && 
        record.quantity > 0
      )
      
      // 计算统计数据
      this.calculateStats(validRecords)
      
      this.setData({
        records: validRecords,
        loading: false,
        hasMore: validRecords.length >= 20 // 假设每页20条
      })
    }).catch((err) => {
      console.error('获取记录失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取记录失败',
        icon: 'none'
      })
    })
  },

  // 加载更多记录
  loadMoreRecords() {
    if (this.data.loading || !this.data.hasMore) return

    this.setData({
      loading: true
    })

    const nextPage = this.data.currentPage + 1

    app.userRequest({
      url: '/getRecords',
      data: {
        page: nextPage,
        start_date: this.data.dateRange.start,
        end_date: this.data.dateRange.end
      }
    }).then((res) => {
      // 修复：使用正确的数据字段
      const newRecords = res.data?.list || res.data || []
      console.log('加载更多报工记录:', newRecords)
      
      // 过滤掉不完整的记录
      const validNewRecords = newRecords.filter(record => 
        record.order_no && 
        record.process_name && 
        record.quantity > 0
      )
      
      const allRecords = [...this.data.records, ...validNewRecords]
      
      // 重新计算统计数据
      this.calculateStats(allRecords)
      
      this.setData({
        records: allRecords,
        currentPage: nextPage,
        hasMore: validNewRecords.length >= 20,
        loading: false
      })
    }).catch((err) => {
      console.error('加载更多记录失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '加载更多失败',
        icon: 'none'
      })
    })
  },

  // 选择开始日期
  onStartDateChange(e) {
    this.setData({
      'dateRange.start': e.detail.value
    })
  },

  // 选择结束日期
  onEndDateChange(e) {
    this.setData({
      'dateRange.end': e.detail.value
    })
  },

  // 搜索记录
  searchRecords() {
    this.setData({
      currentPage: 1,
      hasMore: true
    })
    this.loadRecords()
  },

  // 重置搜索
  resetSearch() {
    this.setData({
      dateRange: {
        start: '',
        end: ''
      },
      currentPage: 1,
      hasMore: true
    })
    this.loadRecords()
  },

  // 计算统计数据
  calculateStats(records) {
    let totalQuantity = 0
    let totalWage = 0
    let pendingCount = 0

    records.forEach(record => {
      // 总报工数量
      totalQuantity += parseInt(record.quantity) || 0
      
      // 总工资
      totalWage += parseFloat(record.wage) || 0
      
      // 待审核数量
      if (record.status !== 1) {
        pendingCount++
      }
    })

    this.setData({
      totalQuantity: totalQuantity,
      totalWage: totalWage.toFixed(2),
      pendingCount: pendingCount
    })

    console.log('统计数据计算完成:', {
      totalQuantity,
      totalWage,
      pendingCount
    })
  },

  // 刷新记录
  refreshRecords() {
    this.setData({
      currentPage: 1,
      hasMore: true
    })
    this.loadRecords()
  },

  // 预览图片
  previewImage(e) {
    e.stopPropagation() // 阻止事件冒泡
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      current: current,
      urls: urls
    })
  },

  // 跳转到记录详情页面
  goToRecordDetail(e) {
    console.log('点击了记录卡片', e)
    const record = e.currentTarget.dataset.record
    console.log('记录数据:', record)
    
    if (!record) {
      console.error('没有获取到记录数据')
      wx.showToast({
        title: '数据错误',
        icon: 'none'
      })
      return
    }

    // 将记录数据转换为URL参数
    const recordData = encodeURIComponent(JSON.stringify(record))
    console.log('准备跳转到详情页面:', `/pages/record-detail/record-detail?record=${recordData}`)
    
    wx.navigateTo({
      url: `/pages/record-detail/record-detail?record=${recordData}`,
      success: () => {
        console.log('跳转成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  }
}) 